package com.mxm.mirai.bot;

import com.mxm.mirai.config.MXM_config;
import com.mxm.mirai.service.BotgroupsService;
import com.mxm.mirai.tools.BotTools;
import net.dreamlu.mica.http.HttpRequest;
import net.mamoe.mirai.contact.Group;
import net.mamoe.mirai.message.GroupMessageEvent;
import net.mamoe.mirai.message.data.Image;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.awt.image.BufferedImage;
import java.net.URLEncoder;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Component
public class BotBaiDu implements Consumer<GroupMessageEvent> {

    @Autowired
    BotgroupsService botgroupsService;

    private static BotBaiDu botBaiDu;
    @PostConstruct
    public void init(){
        botBaiDu=this;
        botBaiDu.botgroupsService = this.botgroupsService;
    }

//    public static final AtomicBoolean isRunning = new AtomicBoolean(false);
//
//    public static final AtomicReference<Long> runningQQ = new AtomicReference(0L);
//
//    public static final AtomicReference<Long> runningGroup = new AtomicReference(0L);

    private static Map<String,Object> mapdata=null;
    private static BotBaiDuData botBaiDuData = new BotBaiDuData();
    private static Map<String,Object> QQIdGroupId=new HashMap();
    private static BotTools botTools = new BotTools();
//    public static int step = 0;

    @Override
    public void accept(GroupMessageEvent event) {
        if("0".equals(botBaiDu.botgroupsService.QueryBotGroupsState(String.valueOf(event.getBot().getId()),String.valueOf(event.getGroup().getId()),"BotBaiDu"))){return;}
        Group group = event.getGroup();//群类
        String message = event.getMessage().contentToString();//群消息
        long groupId = group.getId();//群号
        long qq = event.getSender().getId();//群发送人号
        botBaiDuData = (BotBaiDuData) QQIdGroupId.get(qq+""+groupId);
        botBaiDuData = botBaiDuData==null?botBaiDuData=new BotBaiDuData():botBaiDuData;
        botBaiDuData.setRunning(true);
        botBaiDuData.setRunningQQ(qq);
        botBaiDuData.setRunningGroup(groupId);
        if (message.length() > 2 && "百度".equals(message.substring(0,2))) {
            stepA(group,groupId,qq,message);
        }else if(botBaiDuData.getStep() == 1){
            stepB(group,groupId,qq, message);
        }
    }
    private void stepA(Group api, long groupId, long qq, String message) {
        try{
            botBaiDuData.setStep(1);
            QQIdGroupId.put(qq+""+groupId,botBaiDuData);
            String text = getBaiDu(message.substring(2,message.length()));
            System.out.println("搜索结果:"+text);
            BufferedImage imgio = botTools.TextTurnImage(text);
            Image img = api.uploadImage(imgio);
            api.sendMessage(img);
//            api.sendMessage(getBaiDu(message.substring(2,message.length())));
            }catch (Exception e){
            botBaiDuData.setStep(0);
            }
    }
    private void stepB(Group api,long groupId,long qq, String message) {
        if (MXM_config.bottools.isNumeric(message) && qq == botBaiDuData.getRunningQQ() && groupId==botBaiDuData.getRunningGroup()) {
            try {
                Map map = (Map) botBaiDuData.getMapdata().get(message);
                api.sendMessage(map.get("title")+"\n"+MXM_config.bottools.DwzUrl(map.get("url").toString()));
            }catch (Exception e){
                botBaiDuData.setStep(0);
            }finally {
                botBaiDuData.setStep(0);
            }
        }
    }
    private static String getBaiDu(String name){
        String html="",text="";
        try {
            html= HttpRequest.get("https://www.baidu.com/s?&wd=" + URLEncoder.encode(name, "UTF-8"))
                    .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.87 Safari/537.36")
                    .addHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3")
                    .addHeader("Upgrade-Insecure-Requests", "1")
                    .addHeader("Connection", "keep-alive")
                    .addHeader("Host", "www.baidu.com")
                    .connectTimeout(Duration.ofSeconds(120))
                    .execute().asString();
            //System.out.println(html);
        }catch (Exception e){
            return "百度搜索失败！";
        }
        Matcher m = Pattern.compile("\"title\":\"(.*?)\",\"url\":\"(.*?)\"").matcher(html);
        mapdata = new HashMap();
        Map map=null;
        int index = 0;
        while (m.find()) {
            if(!m.group(1).contains("+r+")){
                map=new HashMap();
                index+=1;
                text+=index+"."+m.group(1)+"\n";
                map.put("title",m.group(1));
                map.put("url",m.group(2));
                mapdata.put(String.valueOf(index),map);
                //System.out.println(m.group(1)+"___"+m.group(2));
            }
        }
        botBaiDuData.setMapdata(mapdata);
        return "".equals(text)?"百度搜索失败！":text+"[回复数字可快捷选择]";
    }

//    public static void main(String[] args) {
//        String text = getBaiDu("漫小猫");
//        System.out.println(text);
//        BufferedImage imgio =  botTools.TextTurnImage(text);
//        botTools.Xsimg(botTools.bufferedImageToInputStream(imgio));
//    }
}
class BotBaiDuData{
    private Boolean isRunning;
    private Long runningQQ;
    private Long runningGroup;
    private Integer step = 0;
    private Map<String,Object> mapdata;

    public Boolean getRunning() {
        return isRunning;
    }

    public void setRunning(Boolean running) {
        isRunning = running;
    }

    public Long getRunningQQ() {
        return runningQQ;
    }

    public void setRunningQQ(Long runningQQ) {
        this.runningQQ = runningQQ;
    }

    public Long getRunningGroup() {
        return runningGroup;
    }

    public void setRunningGroup(Long runningGroup) {
        this.runningGroup = runningGroup;
    }

    public Integer getStep() {
        return step;
    }

    public void setStep(Integer step) {
        this.step = step;
    }

    public Map<String, Object> getMapdata() {
        return mapdata;
    }

    public void setMapdata(Map<String, Object> mapdata) {
        this.mapdata = mapdata;
    }
}